package cn.tom.config;

import cn.tom.dao.UserDao;
import cn.tom.entity.XUser;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;

@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    private UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username)  {
        log.info("MyUserDetailsService 获取用户信息处理: 用户账号 "+username);
        XUser user = findAccountOrPhone(username);
        if (user == null){
            log.error("无法根据用户账号获取用户信息");
            throw new UsernameNotFoundException("无法根据用户账号获取用户信息");
        }
        if (user.getClosed() == 1) {
            throw new UsernameNotFoundException("账号已冻结");
        }
        log.info("数据库获取用户信息结果：" + user);
        user.setUsername(username);
        return user;
    }

    private XUser findAccountOrPhone(String username){
        XUser myUser = userDao.findByAccount(username);
        if (myUser == null){
            myUser = userDao.findByPhone(username);
        }
        log.info("数据库获取用户信息结果：" + myUser);
        return myUser;
    }
}
